package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.http.HttpRequest;
import java.util.Enumeration;

public class RemoveProductFromCartServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        String[] ids = request.getParameterValues("ids");
        if(ids == null)
        {
            return;
        }
        HttpSession httpSession = request.getSession();
        Account account = (Account)httpSession.getAttribute("account");
        Cart cart = (Cart)httpSession.getAttribute("cart");
        for (String id : ids) {
            httpSession.removeAttribute("cart." + id);
            cart.removeItemById(id);
            if (account != null) {
                CatalogService.deleteCart(account, id);
            }
        }
        httpSession.setAttribute("cart.subTotal",cart.getSubTotal());
        httpSession.setAttribute("cart",cart);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws  IOException,ServletException
    {
        doPost(request,response);
    }

}
